//
//  AuthenPendingVC.swift
//  kxf
//
//  Created by Mac on 2024/3/10.
//

import Foundation
import MJRefresh
import MCToast

class AuthenPendingVC: WHBaseViewVC {
    
    var pageNum = 1
    var status = "0"
    var pageSize = 5
    var keywords = ""
    
    var dataSourceArray = NSMutableArray()
    var pendingStatus = AUTHEN_PENDGING_STATUS.status_ruwang_ing
    
    var updateDict = NSDictionary()
    var updateIndexPath = IndexPath()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        initUI()
        sendListRequest()
    }
    lazy var typeVm : AuthenPendingTypeVM = {
        let vm = AuthenPendingTypeVM.init(frame: CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: 0, height: 0))
        vm.typeChangeBlock = {(type)in
            self.pendingStatus = type
            self.dataSourceArray.removeAllObjects()
            self.tableView.reloadData()
            self.pageNum = 1
            switch type{
            case .status_ruwang_ing:
                self.status = "0"
                break
            case .status_check_ing:
                self.status = "1"
                break
            case .status_authori_ing:
                self.status = "2"
                break
            case .status_refuse:
                self.status = "-1"
                break
            }
            self.sendListRequest()
            }
        
        return vm
    }()
    
    lazy var searchVm : SearchVM = {
        let vm = SearchVM.init(frame: CGRect.init(x: 0, y: self.typeVm.frame.maxY + kFitWidth(10), width: 0, height: 0))
        vm.textField.placeholder = "请输入手机号搜索"
        vm.textField.keyboardType = .numberPad
        vm.backgroundColor = WHColor_16(colorStr: "EFEFEF")
        vm.searchBlock = {()in
            self.keywords = self.searchVm.textField.text ?? ""
            self.pageNum = 1
            self.sendListRequest()
        }
        return vm
    }()
    lazy var tableView : UITableView = {
        let vi = UITableView.init(frame: CGRect.init(x: 0, y: self.searchVm.frame.maxY+kFitWidth(10), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-(self.searchVm.frame.maxY+kFitWidth(10))), style: .plain)
        vi.delegate = self
        vi.dataSource = self
        vi.separatorStyle = .none
        vi.backgroundColor = .COLOR_LIGHT_GREY
        
        vi.register(AuthenPendingRuWangCell.classForCoder(), forCellReuseIdentifier: "AuthenPendingRuWangCell")
        vi.register(AuthenPendingAuthoriCell.classForCoder(), forCellReuseIdentifier: "AuthenPendingAuthoriCell")
        vi.register(AuthenPendingRefuseCell.classForCoder(), forCellReuseIdentifier: "AuthenPendingRefuseCell")
        vi.register(AuthenPendingCheckingCell.classForCoder(), forCellReuseIdentifier: "AuthenPendingCheckingCell")
        
        if #available(iOS 11.0, *) {
            vi.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        
        vi.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.pageNum = 1
            self.sendListRequest()
        })

        vi.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: {
            self.pageNum += 1
            self.sendListRequest()
        })
        
        return vi
    }()
    lazy var emptyView : EmptyViewWithBtn = {
        let emptyViewT = EmptyViewWithBtn.init(frame: CGRect.zero)
        emptyViewT.isHidden = true
        emptyViewT.contentLabel.text = "还没有记录~"
        
        return emptyViewT
    }()
    
    lazy var choiceTypeAlertVm : ChoiceMercTypeAlertVM = {
        let vm = ChoiceMercTypeAlertVM.init(frame: .zero)
        vm.isHidden = true
        vm.tapBlock = {(typeString)in
            DLLog(message: "\(typeString)")
            var merchantType = ""
            if typeString == "mini"{
                merchantType = "1"
            }else if typeString == "geti"{
                merchantType = "2"
            }else if typeString == "qiye"{
                merchantType = "0"
            }
            self.sendUpdateMercTypeRequest(type: merchantType)
        }
        return vm
    }()
}

extension AuthenPendingVC{
    func initUI() {
        initNavi(titleStr: "商户信息管理")
        view.backgroundColor = .COLOR_LIGHT_GREY
        
        view.addSubview(typeVm)
        view.addSubview(searchVm)
        
        view.addSubview(tableView)
        tableView.addSubview(emptyView)
        emptyView.center = CGPoint.init(x: SCREEN_WIDHT*0.5, y: self.tableView.frame.height*0.5)
        
        
        view.addSubview(choiceTypeAlertVm)
    }
}

extension AuthenPendingVC:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        emptyView.isHidden = dataSourceArray.count > 0 ? true : false
        return dataSourceArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dict = self.dataSourceArray[indexPath.row] as? NSDictionary ?? [:]
        if self.pendingStatus == .status_ruwang_ing{
           let cell = tableView.dequeueReusableCell(withIdentifier: "AuthenPendingRuWangCell") as! AuthenPendingRuWangCell
            cell.updateUI(dict: dict)
            cell.editBlock = {()in
                self.sendGetMsgRequset(tel: "\(dict["phone"]as? String ?? "")")
            }
            cell.changeTypeBlock = {()in
                self.choiceTypeAlertVm.isHidden = false
                self.updateDict = dict
                self.updateIndexPath = indexPath
            }
            
            return cell
        }else if self.pendingStatus == .status_authori_ing{
           let cell = tableView.dequeueReusableCell(withIdentifier: "AuthenPendingAuthoriCell") as! AuthenPendingAuthoriCell
            cell.updateUI(dict: dict)
            cell.authoriBlock = {()in
                let vc = AuthoriVC()
                vc.phone = dict["phone"]as? String ?? ""
                self.navigationController?.pushViewController(vc, animated: true)
//                self.presentAlertVcNoAction(title: "去授权", viewController: self)
            }
            return cell
        }else if self.pendingStatus == .status_refuse{
            let cell = tableView.dequeueReusableCell(withIdentifier: "AuthenPendingRefuseCell") as! AuthenPendingRefuseCell
            cell.updateUI(dict: dict)
            cell.showRefuseBlock = {()in
                self.presentAlertVc(confirmBtn: "确定", message: "\(dict["failResult"]as? String ?? "")", title: "驳回原因", cancelBtn: nil, handler: { action in
                    
                }, viewController: self)
            }
            cell.changeTypeBlock = {()in
                self.choiceTypeAlertVm.isHidden = false
                self.updateDict = dict
                self.updateIndexPath = indexPath
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "AuthenPendingCheckingCell") as! AuthenPendingCheckingCell
            cell.updateUI(dict: dict)
            cell.queryBlock = {()in
                self.sendQueryStatusRequest(dict: dict)
            }
            return cell
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.pendingStatus == .status_check_ing{
            return kFitWidth(110)
        }
        return kFitWidth(138)
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.pendingStatus == .status_refuse{
            let dict = self.dataSourceArray[indexPath.row]as? NSDictionary ?? [:]
            self.sendGetMsgRequset(tel: "\(dict["phone"]as? String ?? "")")
        }
    }
}

extension AuthenPendingVC{
    func sendListRequest() {
        let urlParams = "?phone=\(keywords)&pageNum=\(pageNum)&status=\(status)&pageSize=\(pageSize)"
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: "\(URL_pos_user_list)\(urlParams)") { responseObject in
            DLLog(message: "\(responseObject)")
            
            self.tableView.mj_footer!.endRefreshing()
            self.tableView.mj_header!.endRefreshing()
            
            if responseObject["code"]as? Int ?? -1 == 200{
                let dataDict = responseObject["data"]as? NSDictionary ?? [:]
                let dataArr = dataDict["list"]as? NSArray ?? []
                
                if self.pageNum == 1{
                    self.dataSourceArray.removeAllObjects()
                }
                // 提示没有更多数据
                if dataArr.count < self.pageSize {
                    self.tableView.mj_footer!.endRefreshingWithNoMoreData()
                }
                
                self.dataSourceArray.addObjects(from: dataArr as! [Any])
                self.tableView.reloadData()
            }else{
                
            }
        }
    }
    func sendQueryStatusRequest(dict:NSDictionary) {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: "\(URL_authen_msg_confirm)?phone=\(dict["phone"]as? String ?? "")&type=\(dict["type"]as? Int ?? 0)") { responseObject in
            DLLog(message: "\(responseObject)")
            if (responseObject["message"]as? String ?? "").count > 0 {
                MCToast.mc_text("\(responseObject["message"]as? String ?? "")")
            }
        }
    }
    func sendUpdateMercTypeRequest(type:String) {
        MCToast.mc_loading()
        let param:[String:String] = ["merchantType":"\(type)",
                                     "tel":"\(self.updateDict["phone"]as? String ?? "")"]
        WHNetworkUtil.shareManager().POST(urlString: URL_authen_msg_save, parameters: param as [String:AnyObject]) { responseObject in
            DLLog(message: "\(responseObject)")
            
            let dict = NSMutableDictionary.init(dictionary: self.updateDict as! [AnyHashable : Any], copyItems: true)
            dict["mchType"] = "\(type)"
            self.dataSourceArray.replaceObject(at: self.updateIndexPath.row, with: dict)
            self.tableView.reloadRows(at: [self.updateIndexPath], with: .left)
            
        }
    }
    func sendGetMsgRequset(tel:String) {
        MCToast.mc_loading()
        let urlString = "\(URL_authen_msg_query)?tel=\(tel)"
        
        WHNetworkUtil.shareManager().GET(urlString: urlString,vc:self) { responseObject in
            DLLog(message: "\(responseObject)")
            
            let dataObj = responseObject["data"]as? NSDictionary ?? [:]
            UserModel.shared.posChannel = dataObj["posChannel"]as? String ?? "ys"
            if dataObj["merchantType"]as? String ?? "" == "0" {
                AuthenCompanyMsgModel.shareInstance.refreshMsg(dict: responseObject["data"]as? NSDictionary ?? [:])
                
                if AuthenCompanyMsgModel.shareInstance.posChannel == "fy"{
                    let vc = AuthenCompanyFYVC()
                    vc.isUpdate = true
                    vc.isAgentEdit = true
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    let vc = AuthenCompanyVC()
                    vc.isUpdate = true
                    vc.isAgentEdit = true
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }else if dataObj["merchantType"]as? String ?? "" == "1" {
                AuthenMiniMsgModel.shareInstance.refreshMsg(dict: responseObject["data"]as? NSDictionary ?? [:])
                let vc = AuthenMiniVC()
                vc.isUpdate = true
                vc.isAgentEdit = true
                self.navigationController?.pushViewController(vc, animated: true)
            }else if dataObj["merchantType"]as? String ?? "" == "2" {
                AuthenCompanyMsgModel.shareInstance.refreshMsg(dict: responseObject["data"]as? NSDictionary ?? [:])
                let vc = AuthenGeTiVC()
                vc.isUpdate = true
                vc.isAgentEdit = true
                self.navigationController?.pushViewController(vc, animated: true)
            }else {
                AuthenMiniMsgModel.shareInstance.refreshMsg(dict: responseObject["data"]as? NSDictionary ?? [:])
                let vc = AuthenMiniVC()
                vc.isUpdate = true
                vc.isAgentEdit = true
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
}
